<template>
  <view class="confirm-order-container">
    <!-- 收货地址部分 -->
    <view class="address-section" @click="goToAddressPage">
      <text class="section-title">收货地址</text>
      <view v-if="selectedAddress" class="address-info">
        <text>{{ selectedAddress.city }} {{ selectedAddress.department }} {{ selectedAddress.houseNumber }}</text>
        <text>{{ selectedAddress.name }} {{ selectedAddress.phone }}</text>
      </view>
    </view>

    <!-- 商品列表部分（按超市分组） -->
    <view class="product-section">
      <view v-for="(products, storeName) in groupedProducts" :key="storeName" class="store-group">
        <view class="store-name">{{ storeName }}</view>
        <view v-for="(product, index) in products" :key="index" class="product-item">
          <image class="product-img" :src="product.item.imgUrl" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ product.item.name }}</text>
            <text class="product-sales">月售 {{ product.item.sales }} 件</text>
            <view class="price-section">
              <text class="price-current">¥{{ product.item.price }}</text>
              <text class="price-old"></text>
            </view>
            <text class="quantity-text">数量: {{ product.orderSales }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 结算总价和提交订单按钮 -->
    <view class="checkout-footer">
      <view class="checkout-total">
        <text>结算总价: ¥{{ totalPrice }}</text>
      </view>
      <view class="submit-order-btn" @click="submitOrder">
        <text>提交订单</text>
      </view>
    </view>
  </view>
</template>

<script>
	import  config  from '@/config'
export default {
  data() {
    return {
      receivedCartList: [],
      addressList: [],
      totalPrice: 0,
      stores: [],
      selectedAddress: {},
      isSubmitting: false
    };
  },
  onShow() {
    const selectedAddress = uni.getStorageSync('selectedAddress');
    if (selectedAddress) {
      this.selectedAddress = selectedAddress;
      uni.removeStorageSync('selectedAddress');
    }
  },
  computed: {
    groupedProducts() {
      const grouped = {};
      console.log(this.receivedCartList,2)
      this.receivedCartList.forEach(item => {
        const storeName = item.storeName;
        if (!grouped[storeName]) {
          grouped[storeName] = [];
        }
          const productData = {
                item,
                orderSales: item.quantity
          }
          grouped[storeName].push(productData);
        }); 
      console.log(grouped,1)
      return grouped;
    }
  },
  onLoad(options) {
    if (options) {
      try {
        const cartListString = decodeURIComponent(options.selectedItems);
        this.receivedCartList = JSON.parse(cartListString);
        console.log(this.receivedCartList,2)
        this.calculateTotalPrice();
      } catch (error) {
        console.error('解析购物车数据出错:', error);
        uni.showToast({
          title: '解析购物车数据失败',
          icon: 'none'
        });
      }
    }
    this.fetchAddressList();
    this.fetchAllStores();
  },
  methods: {
    fetchAddressList() {
      uni.request({
        url: config.API_HOST+'/adress',
        timeout: 5000,
        success: (res) => {
          this.addressList = res.data;
          if (this.addressList.length > 0) {
            this.selectedAddress = this.addressList[0];
          }
        },
        fail: (error) => {
          console.error('获取收货地址列表出错:', error);
          uni.showToast({
            title: '获取收货地址列表失败',
            icon: 'none'
          });
        }
      });
    },
    fetchAllStores() {
      uni.request({
        url: config.API_HOST+'/adress',
        timeout: 5000,
        success: (res) => {
          this.stores = res.data;
        },
        fail: (error) => {
          console.error('获取店铺信息出错:', error);
          uni.showToast({
            title: '获取店铺信息失败',
            icon: 'none'
          });
        }
      });
    },
    calculateTotalPrice() {
    this.totalPrice = this.receivedCartList.reduce((acc, item) => {
        const price = item.price;
        const quantity = item.quantity;
        if (price && quantity) {
            return acc + (price * quantity);
        }
        return acc;
    }, 0).toFixed(2);
},
    goToAddressPage() {
      uni.navigateTo({
        url: '/pages/me/address'
      });
    },
submitOrder() {
  if (this.isSubmitting) return;
  this.isSubmitting = true;
  uni.showLoading({
    title: '提交中...'
  });
  uni.showModal({
    title: '提交订单',
    content: `是否确认订单`,
    success: (res) => {
      if (res.confirm) {
        const orderData = {
          address: {
            city: this.selectedAddress.city,
            department: this.selectedAddress.department,
            houseNumber: this.selectedAddress.houseNumber,
            name: this.selectedAddress.name,
            phone: this.selectedAddress.phone
          },
          shopId: this.receivedCartList[0]?.superId || '',
          shopName: this.receivedCartList[0]?.storeName || '',
          isCanceled: '1', 
          products: this.receivedCartList.map(item => ({
            orderSales: item.quantity,
            product: {
              name: item.name,
              img: item.imgUrl,
              price: item.price,
              sales: item.sales
            }
          })),
          orderTime: this.formatDate(new Date())
        };

        uni.request({
          url: config.API_HOST+'/order0',
          method: 'POST',
          data: orderData,
          timeout: 5000,
          success: (res) => {
            console.log('订单提交成功:', res.data);
            this.clearCheckedItems();
            uni.showToast({
              title: '订单提交成功',
              icon:'success'
            });
            uni.switchTab({
              url: '/pages/order/index'
            });
            let cartItems = uni.getStorageSync('cartItems')|| [];
            cartItems =cartItems.filter(item => !item.isSelected);
            uni.setStorageSync('cartItems', cartItems);
          },
          fail: (error) => {
            console.error('订单提交失败:', error);
            uni.showToast({
              title: '订单提交失败',
              icon: 'none'
            });
          },
          complete: () => {
            this.isSubmitting = false;
            uni.hideLoading();
          }
        });
      } else {
        this.isSubmitting = false;
        uni.hideLoading();
      }
    }
  });
},
    clearCheckedItems() {
      try {
        const savedCart = JSON.parse(localStorage.getItem('cartList')) || {};
        const newCart = {};
        this.receivedCartList.forEach(item => {
          const storeId = item.shopId;
          if (savedCart[storeId]) {
            const remainingItems = savedCart[storeId].filter(cartItem => {
              return!this.receivedCartList.some(orderItem =>
                orderItem.products.some(p => p.product._id === cartItem.product._id)
              );
            });
            if (remainingItems.length > 0) {
              newCart[storeId] = remainingItems;
            }
          }
        });
        localStorage.setItem('cartList', JSON.stringify(newCart));
      } catch (e) {
        console.error('清除已结算商品失败:', e);
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    }
  }
};
</script>

<style scoped>
.confirm-order-container {
  padding: 15px;
  background-color: #f8f8f8;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 地址部分样式 */
.address-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}
.address-info {
  font-size: 14px;
  line-height: 1.6;
}
.address-info text {
  display: block;
}

/* 商品部分样式 */
.product-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.store-group {
  margin-bottom: 15px;
}
.store-name {
  font-size: 15px;
  font-weight: bold;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
  color: #333;
}
.product-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
}
.product-item:last-child {
  border-bottom: none;
}
.product-img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  margin-right: 12px;
}
.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.product-name {
  font-size: 15px;
  color: #333;
  line-height: 1.4;
}
.product-sales {
  font-size: 12px;
  color: #999;
}
.price-section {
  display: flex;
  align-items: center;
  margin: 5px 0;
}
.price-current {
  font-size: 16px;
  color: #ff6700;
  font-weight: bold;
  margin-right: 8px;
}
.price-old {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}
.quantity-text {
  font-size: 14px;
  color: #666;
  align-self: flex-end;
}

/* 结算总价和提交订单按钮样式 */
.checkout-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  left: 0;
  background-color: #fff;
  padding: 12px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
}

.checkout-total {
  font-size: 16px;
  font-weight: bold;
  color: #ff6700;
}

.submit-order-btn {
  background-color: #ff6700;
  padding: 8px 20px;
  border-radius: 4px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
</style>